﻿#region License
/* ---------------------------------------------------------------- *
 *
 * This file is part of the Xcoordination Application Space
 * ("XcoAppSpace") http://www.xcoordination.com
 *
 * Copyright (C) 2009 Xcoordination http://www.xcoordination.com
 *
 * XcoAppSpace is free software; you can redistribute it and/or
 * modify it under the terms of version 2 of the GNU General
 * Public License as published by the Free Software Foundation.
 *
 * XcoAppSpace is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses/
 * or write to the Free Software Foundation, Inc., 51 Franklin
 * Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * ---------------------------------------------------------------- */
#endregion

using System;
using System.Collections.Generic;
using XcoAppSpaces.Contracts.Service;
using XcoAppSpaces.Contracts.Exceptions;

namespace XcoAppSpaces.Transport.Sockets
{
	/// <summary>
	/// Configuration string interpreter for the XcoTCPTransportService.
	/// </summary>
    public class ConfigStringInterpreter : XcoConfigStringInterpreterBase
	{
		/// <summary>
		/// Config key for setting the port.
		/// </summary>
		public const string ConfigPort = "tcp.port";
		/// <summary>
		/// Config key for setting the connection lifetime (format: mm:ss).
		/// </summary>
		public const string ConfigLifetime = "tcp.lifetime";
		/// <summary>
		/// Config key for setting the name.
		/// </summary>
		public const string ConfigName = "tcp.name";
		/// <summary>
		/// Config key for setting if the service is the default communication service.
		/// </summary>
		public const string ConfigIsDefault = "tcp.isdefault";
		/// <summary>
		/// Config key for setting the authentication key.
		/// </summary>
		public const string ConfigAuthKey = "tcp.key";
		

        private int? _port;
		private TimeSpan? _lifetime;
		private string _name;
        private bool? _isdefault;
		private string _authkey;
        
		/// <summary>
        /// Action definition for interpretion
        /// </summary>
        public override Dictionary<string, Action<string>> InterpretDefinition
        {
            get
            {
                return new Dictionary<string, Action<string>> 
                    { 
                        {ConfigPort, AnalysePort},//Configuration key for setting the port.
                        {ConfigLifetime, AnalyseLifetime},//Configuration key for setting the lifetime.
                        {ConfigName, AnalyseName},//Configuration key for setting the name.
                        {ConfigIsDefault, AnalyseIsDefault},//Configuration key for setting if the service is the default communication service.
						{ConfigAuthKey, x => _authkey = x},
                    };
            }
        }

        /// <summary>
        /// Get the current tcp service
        /// </summary>
        public override IXcoService GetService
        {
            get
            {
                if (_port != null || _name != null || _isdefault != null || _lifetime != null)
                {
                    if (_name != null)
                    {
                        ServiceConfig.Name = _name;
                    }
					if (_isdefault != null)
                    {
                        ServiceConfig.IsDefault = _isdefault.Value;
                    }
#if SILVERLIGHT
					var service = new XcoTCPTransportService(); //no port configuration in silverlight...
#else

                    var service =  _port.HasValue
                               ? new XcoTCPTransportService(_port.Value)
                               : new XcoTCPTransportService();
#endif
					if (_lifetime != null)
					{
						service.ConnectionLifetime = _lifetime.Value;
					}

					if (_authkey != null)
						service.SecuritySettings.AuthenticationKey = _authkey;

					return service;
				}
                return null;
            }
        }

        #region analyse methods

        void AnalysePort(string portStr)
        {
            //try to load port-definition from the configuration
            int tmpPort;
			if (TryParse(portStr, out tmpPort))
            {
				if (tmpPort < 0)
					throw new XcoConfigurationException("Port cannot be a negative number.");
                _port = tmpPort;
            }
            else
            {
                throw new XcoConfigurationException("Port must be a number.");
            }
        }

		void AnalyseLifetime(string lifetimeStr)
		{
			var parts = lifetimeStr.Split(':');
			if (parts.Length != 2)
				throw new XcoConfigurationException("Lifetime must be a value in the format \"mm:ss\".");

			int minutes;
			int seconds;
			if (!TryParse(parts[0], out minutes) || !TryParse(parts[1], out seconds))
				throw new XcoConfigurationException("Lifetime must be a value in the format \"mm:ss\".");

			_lifetime = new TimeSpan(0, minutes, seconds);
		}

		private bool TryParse(string str, out int number)
		{
#if PocketPC
			return ParseHelper.TryParse(str, out number);
#else
			return int.TryParse(str, out number);
#endif
		}

        void AnalyseName(string name)
        {
           _name = name;
        }

        void AnalyseIsDefault(string isDefaultStr)
        {
            bool tmpIsDefault;
#if PocketPC
			if (ParseHelper.TryParse(isDefaultStr, out tmpIsDefault))
#else
			if (bool.TryParse(isDefaultStr, out tmpIsDefault))
#endif
			{ //try to load the isDefault-definition from the configuration
                _isdefault = tmpIsDefault;
            }
            else
            {
                throw new XcoConfigurationException("IsDefault must be either \"true\" or \"false\"!");
            }
        }
        #endregion


    }
}
